<template>
  <div class="member-container">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" inline>
        <el-form-item label="会员账号">
          <el-input v-model="searchForm.username" placeholder="请输入会员账号" clearable />
        </el-form-item>
        <el-form-item label="会员昵称">
          <el-input v-model="searchForm.nickname" placeholder="请输入会员昵称" clearable />
        </el-form-item>
        <el-form-item label="会员等级">
          <el-select v-model="searchForm.level" placeholder="请选择会员等级" clearable>
            <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="会员状态">
          <el-select v-model="searchForm.status" placeholder="请选择会员状态" clearable>
            <el-option label="正常" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>会员列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">新增会员</el-button>
            <el-upload
              class="upload-demo"
              :auto-upload="false"
              :show-file-list="false"
              accept=".xlsx,.xls"
              :on-change="handleImportChange"
            >
              <el-button type="primary">导入会员</el-button>
            </el-upload>
            <el-button type="warning" @click="handleExport">导出会员</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="memberList"
        style="width: 100%"
        border
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="username" label="会员账号" width="120" />
        <el-table-column prop="nickname" label="会员昵称" width="120" />
        <el-table-column prop="avatar" label="头像" width="80" align="center">
          <template #default="{ row }">
            <el-avatar :size="40" :src="row.avatar" v-if="row.avatar">
              <el-icon><User /></el-icon>
            </el-avatar>
            <el-avatar :size="40" v-else>
              <el-icon><User /></el-icon>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="level" label="会员等级" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)">{{ getLevelLabel(row.level) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分" width="80" align="center" />
        <el-table-column prop="balance" label="余额" width="100" align="center">
          <template #default="{ row }">
            ¥{{ row.balance.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间" width="160" />
        <el-table-column prop="lastLoginTime" label="最后登录" width="160" />
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleDetail(row)">详情</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 会员表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="handleDialogClose"
    >
      <el-form
        ref="memberFormRef"
        :model="memberForm"
        :rules="memberRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="会员账号" prop="username">
              <el-input v-model="memberForm.username" placeholder="请输入会员账号" :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员昵称" prop="nickname">
              <el-input v-model="memberForm.nickname" placeholder="请输入会员昵称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="密码" prop="password" v-if="!isEdit">
              <el-input v-model="memberForm.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword" v-if="!isEdit">
              <el-input v-model="memberForm.confirmPassword" type="password" placeholder="请确认密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="memberForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="memberForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="会员等级" prop="level">
              <el-select v-model="memberForm.level" placeholder="请选择会员等级">
                <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="积分" prop="points">
              <el-input-number v-model="memberForm.points" :min="0" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="余额" prop="balance">
              <el-input-number v-model="memberForm.balance" :min="0" :precision="2" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="memberForm.status">
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadAvatar"
          >
            <img v-if="memberForm.avatar" :src="memberForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="memberForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 会员详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="会员详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="会员账号">{{ detailForm.username }}</el-descriptions-item>
        <el-descriptions-item label="会员昵称">{{ detailForm.nickname }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ detailForm.email }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ detailForm.phone }}</el-descriptions-item>
        <el-descriptions-item label="会员等级">
          <el-tag :type="getLevelTagType(detailForm.level)">{{ getLevelLabel(detailForm.level) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="积分">{{ detailForm.points }}</el-descriptions-item>
        <el-descriptions-item label="余额">¥{{ detailForm.balance.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailForm.status === 1 ? 'success' : 'danger'">
            {{ detailForm.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="注册时间">{{ detailForm.registerTime }}</el-descriptions-item>
        <el-descriptions-item label="最后登录">{{ detailForm.lastLoginTime }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailForm.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, FormRules, UploadRequestOptions } from 'element-plus'
import { User, Plus } from '@element-plus/icons-vue'
import type { FormInstance, UploadInstance } from 'element-plus'
import { memberApi } from '../../api'

// 会员接口定义
interface Member {
  id?: number
  username: string
  nickname: string
  password?: string
  confirmPassword?: string
  email: string
  phone: string
  avatar?: string
  level: number
  points: number
  balance: number
  status: number
  registerTime?: string
  lastLoginTime?: string
  remark?: string
}

// 响应式数据
const loading = ref(false)
const memberList = ref<Member[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const detailVisible = ref(false)
const isEdit = ref(false)
const searchFormRef = ref<FormInstance>()
const memberFormRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive({
  username: '',
  nickname: '',
  level: '',
  status: '',
  dateRange: [] as string[]
})

// 会员表单
const memberForm = reactive<Member>({
  username: '',
  nickname: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: '',
  avatar: '',
  level: 1,
  points: 0,
  balance: 0,
  status: 1,
  remark: ''
})

// 详情表单
const detailForm = reactive<Member>({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: '',
  level: 1,
  points: 0,
  balance: 0,
  status: 1,
  registerTime: '',
  lastLoginTime: '',
  remark: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 会员等级选项
const levelOptions = [
  { label: '普通会员', value: 1 },
  { label: '白银会员', value: 2 },
  { label: '黄金会员', value: 3 },
  { label: '铂金会员', value: 4 },
  { label: '钻石会员', value: 5 }
]

// 表单验证规则
const memberRules: FormRules = {
  username: [
    { required: true, message: '请输入会员账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入会员昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== memberForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  level: [{ required: true, message: '请选择会员等级', trigger: 'change' }]
}

// 初始化数据
onMounted(() => {
  fetchMemberList()
})

// 获取会员列表
const fetchMemberList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      username: searchForm.username || undefined,
      nickname: searchForm.nickname || undefined,
      level: searchForm.level !== undefined ? searchForm.level : undefined,
      status: searchForm.status !== undefined ? searchForm.status : undefined,
      startTime: searchForm.registerTime && searchForm.registerTime.length > 0 ? searchForm.registerTime[0] : undefined,
      endTime: searchForm.registerTime && searchForm.registerTime.length > 0 ? searchForm.registerTime[1] : undefined
    }
    
    // 调用API获取会员列表
    const res = await memberApi.getMemberList(params)
    
    if (res.code === 200) {
      memberList.value = res.data.list || []
      pagination.total = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取会员列表失败')
    }
  } catch (error) {
    console.error('获取会员列表失败:', error)
    ElMessage.error('获取会员列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索会员
const handleSearch = () => {
  pagination.currentPage = 1
  fetchMemberList()
}

// 重置搜索
const resetSearch = () => {
  if (searchFormRef.value) {
    searchFormRef.value.resetFields()
  }
  handleSearch()
}

// 新增会员
const handleAdd = () => {
  resetForm()
  isEdit.value = false
  dialogTitle.value = '新增会员'
  dialogVisible.value = true
}

// 编辑会员
const handleEdit = (row: Member) => {
  resetForm()
  isEdit.value = true
  dialogTitle.value = '编辑会员'
  Object.assign(memberForm, row)
  dialogVisible.value = true
}

// 查看会员详情
const handleDetail = (row: Member) => {
  Object.assign(detailForm, row)
  detailVisible.value = true
}

// 删除会员
const handleDelete = async (row: Member) => {
  try {
    await ElMessageBox.confirm('确认删除该会员吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用API删除会员
    const res = await memberApi.deleteMember(row.id)
    
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchMemberList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除会员失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 修改会员状态
const handleStatusChange = async (row: Member) => {
  try {
    // 调用API修改会员状态
    const res = await memberApi.updateMemberStatus({
      id: row.id,
      status: row.status
    })
    
    if (res.code === 200) {
      const statusText = row.status === 1 ? '启用' : '禁用'
      ElMessage.success(`会员${statusText}成功`)
    } else {
      // 恢复原状态
      row.status = row.status === 1 ? 0 : 1
      ElMessage.error(res.message || '状态修改失败')
    }
  } catch (error) {
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
    console.error('修改会员状态失败:', error)
    ElMessage.error('状态修改失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!memberFormRef.value) return
  
  try {
    // 表单验证
    await memberFormRef.value.validate()
    
    // 准备提交数据
    const submitData = { ...memberForm }
    delete submitData.confirmPassword // 删除确认密码字段
    
    let res
    if (isEdit.value) {
      // 编辑会员
      res = await memberApi.updateMember(submitData)
    } else {
      // 新增会员
      res = await memberApi.addMember(submitData)
    }
    
    if (res.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      dialogVisible.value = false
      fetchMemberList()
    } else {
      ElMessage.error(res.message || (isEdit.value ? '修改失败' : '新增失败'))
    }
  } catch (error) {
    if (error !== false) { // 表单验证失败时会返回false
      console.error('提交会员表单失败:', error)
      ElMessage.error(isEdit.value ? '修改失败' : '新增失败')
    }
  }
}

// 重置表单
const resetForm = () => {
  if (memberFormRef.value) {
    memberFormRef.value.resetFields()
  }
  Object.assign(memberForm, {
    username: '',
    nickname: '',
    password: '',
    confirmPassword: '',
    email: '',
    phone: '',
    avatar: '',
    level: 1,
    points: 0,
    balance: 0,
    status: 1,
    remark: ''
  })
}

// 关闭对话框
const handleDialogClose = () => {
  resetForm()
}

// 头像上传前的校验
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 上传头像
const uploadAvatar = async (options: UploadRequestOptions) => {
  try {
    // 调用API上传头像
    const formData = new FormData()
    formData.append('file', options.file)
    
    const res = await memberApi.uploadAvatar(formData)
    
    if (res.code === 200) {
      memberForm.avatar = res.data.url
      ElMessage.success('头像上传成功')
    } else {
      ElMessage.error(res.message || '头像上传失败')
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error('头像上传失败')
  }
}

// 导入会员
const handleImport = async (file: File) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    const res = await memberApi.importMembers(formData)
    
    if (res.code === 200) {
      ElMessage.success(res.message || '导入成功')
      fetchMemberList()
    } else {
      ElMessage.error(res.message || '导入失败')
    }
  } catch (error) {
    console.error('导入会员失败:', error)
    ElMessage.error('导入失败')
  }
}

// 处理导入文件变化
const handleImportChange = (file: any) => {
  if (file.raw) {
    handleImport(file.raw)
  }
}

// 导出会员
const handleExport = async () => {
  try {
    // 构建查询参数
    const params = {
      username: searchForm.username || undefined,
      nickname: searchForm.nickname || undefined,
      level: searchForm.level !== undefined ? searchForm.level : undefined,
      status: searchForm.status !== undefined ? searchForm.status : undefined,
      startTime: searchForm.registerTime && searchForm.registerTime.length > 0 ? searchForm.registerTime[0] : undefined,
      endTime: searchForm.registerTime && searchForm.registerTime.length > 0 ? searchForm.registerTime[1] : undefined
    }
    
    const res = await memberApi.exportMembers(params)
    
    if (res.code === 200) {
      // 创建下载链接
      const link = document.createElement('a')
      link.href = res.data.url
      link.download = res.data.filename || '会员列表.xlsx'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      ElMessage.success('导出成功')
    } else {
      ElMessage.error(res.message || '导出失败')
    }
  } catch (error) {
    console.error('导出会员失败:', error)
    ElMessage.error('导出失败')
  }
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchMemberList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchMemberList()
}

// 获取会员等级标签
const getLevelLabel = (level: number) => {
  const option = levelOptions.find(item => item.value === level)
  return option ? option.label : '未知'
}

// 获取会员等级标签类型
const getLevelTagType = (level: number) => {
  switch (level) {
    case 1: return ''
    case 2: return 'info'
    case 3: return 'success'
    case 4: return 'warning'
    case 5: return 'danger'
    default: return ''
  }
}
</script>

<style scoped>
.member-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

/* 搜索区域样式优化 */
.search-card .el-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-card .el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}

.search-card .el-form-item:last-child {
  margin-right: 0;
}

/* 增加选择框宽度 */
.search-card .el-select {
  width: 150px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 头像上传样式 */
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .member-container {
    padding: 10px;
  }
  
  .el-form-item {
    margin-right: 0;
    width: 100%;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 5px;
  }
  
  .header-actions .el-button {
    margin-left: 0 !important;
    margin-bottom: 5px;
  }
  
  .pagination-container {
    text-align: center;
  }
  
  .el-dialog {
    width: 90% !important;
  }
}
</style>